package com.maple.base.base

import android.app.Activity
import android.content.res.Configuration
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.navigation.NavController
import androidx.navigation.Navigation
import com.blankj.utilcode.util.KeyboardUtils
import com.kongqw.network.monitor.NetworkMonitorManager
import com.kongqw.network.monitor.enums.NetworkState
import com.kongqw.network.monitor.interfaces.NetworkMonitor
import com.maple.base.widget.loading.LoadingDialog
import com.maple.utils.util.LogUtils
import com.maple.utils.util.NetworkUtil
import com.maple.utils.util.ToastUtils
import com.zackratos.ultimatebarx.ultimatebarx.statusBarOnly
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking

abstract class BaseFragment : Fragment(), IView {

    /// 是否第一次加载 用于懒加载
    private var isFirstLoad: Boolean = true

    protected var navController: NavController? = null

    private var loadingDialog: LoadingDialog? = null

    open fun hasNavController(): Boolean = false
    /// 是否使用透明状态栏
    open fun hasStatusBarMode(): Boolean = false
    // 是否使用 监听网络状态变化
    open fun hasNetworkState(): Boolean = false
    abstract fun getLayoutId(): Int

    abstract fun initData(savedInstanceState: Bundle?): Unit

    open fun initView(view: View, savedInstanceState: Bundle?) {
        if (hasNavController()) {
            this.navController = Navigation.findNavController(view)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return setContentLayout(inflater, container, savedInstanceState)
    }

    open fun setContentLayout(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return inflater.inflate(getLayoutId(), container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (hasStatusBarMode()) {
            setStatusBarMode()
        }
        this.initView(view, savedInstanceState)
        this.initData(savedInstanceState)
        if(hasNetworkState()) {
            NetworkMonitorManager.getInstance().register(this)
            val type = if(NetworkUtil.netWorkType() == NetworkUtil.NetType.NET_4G) {
                NetworkState.CELLULAR
            } else if(NetworkUtil.netWorkType() == NetworkUtil.NetType.WIFI) {
                NetworkState.WIFI
            } else {
                NetworkState.NONE
            }
            onNetWorkChange(type)
        }
    }

    open fun setStatusBarMode(color: Int = com.maple.res.R.color.toolbar_bg, fitWindow: Boolean = true, light: Boolean = true) {
        // 只需要设置状态栏，不需要设置导航栏
        statusBarOnly {
            // 布局是否侵入状态栏（true 不侵入，false 侵入）
            this.fitWindow = fitWindow
            // 状态栏背景颜色（资源 id）
            this.colorRes = color
            // light模式：状态栏字体 true: 灰色，false: 白色 Android 6.0+
            this.light = light
        }
    }

    open fun showLoading() {
        if (loadingDialog == null) {
            loadingDialog = context?.let {
                LoadingDialog(it)
            }
        }
        loadingDialog?.run {
            if (!this.isShowing) this.show()
        }
    }

    open fun dismissLoading() {
        loadingDialog?.run {
            if (isShowing) {
                runBlocking {
                    delay(500L)
                }
                dismiss()
            }
        }
    }

    override fun onResume() {
        super.onResume()
        if (isFirstLoad) {
            isFirstLoad = false
            onLazyLoad()
        } else {
            onRestLoad()
        }
    }

    override fun onPause() {
        super.onPause()
        LogUtils.logGGQ("----------onPause-------->>>${this.javaClass.name}")
    }

    open fun onLazyLoad() {
        LogUtils.logGGQ("----------onLazyLoad-------->>>${this.javaClass.name}")
    }

    open fun onRestLoad() {
        LogUtils.logGGQ("----------onRestLoad-------->>>>${this.javaClass.name}")
    }

    /**
     * 返回
     */
    open fun onPopBack() {
        if (hasNavController()) {
            this.navController?.popBackStack()
        }
    }

    open fun onPopResult(result: String) {
        if (hasNavController()) {
            this.navController?.previousBackStackEntry?.savedStateHandle?.set("navDataKey", result)
            this.navController?.popBackStack()
        }
    }

    open fun onNavListenerResult(call: (value: String?) -> Unit) {
        if (hasNavController()) {
            this.navController?.currentBackStackEntry?.savedStateHandle?.getLiveData<String?>("navDataKey")
                ?.observe(viewLifecycleOwner) {
                    call.invoke(it)
                }
        }
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        LogUtils.logGGQ("----------onConfigurationChanged-------->>>${newConfig.orientation}")
    }

    fun hideKeyboard() {
        if (KeyboardUtils.isSoftInputVisible(requireActivity())) {
            KeyboardUtils.hideSoftInput(requireActivity())
        }
    }

    /***
     * 打开新的页面
     * @param clazz 新页面
     * @param bundle 传递bundle 数据,非必填
     * @param isFinish 是否关闭当前页面 默认不关闭
     */
    open fun onStartActivity(
        clazz: Class<out Activity?>,
        bundle: Bundle? = null,
        isFinish: Boolean = false
    ) {
        (this.requireActivity() as BaseActivity).onStartActivity(clazz, bundle, isFinish)
    }

    open fun onFinish() {
        (this.requireActivity() as BaseActivity).onFinish()
    }


    open fun showToast(s: String?) {
        if (this.lifecycle.currentState.isAtLeast(Lifecycle.State.CREATED)) {
            requireActivity().runOnUiThread {
                ToastUtils.showToast(s)
            }
        }
    }


    @NetworkMonitor
    fun onNetWorkStateChange(networkState: NetworkState) {
        requireActivity().runOnUiThread {
            onNetWorkChange(networkState)
        }
    }

    open fun onNetWorkChange(networkState: NetworkState) {}


    override fun onDestroy() {
        super.onDestroy()
        if(hasNetworkState()) {
            NetworkMonitorManager.getInstance().unregister(this)
        }
    }
}